import { useAuthUserStore } from '@/stores/authuserStore';
import { useMenuStore } from '@/stores/menuStore';
import { ElNotification } from 'element-plus';
import { RouteLocationNormalized, Router, RouteRecordRaw } from 'vue-router';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Cookies from 'js-cookie'
import utils from "utils";

// 路由守卫
class RouterWatching {
  public router: Router;
  public bTo: RouteLocationNormalized | undefined;
  public bFrom: RouteLocationNormalized | undefined;

  constructor(router: Router) {
    this.router = router;
    router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized,next) => {
      this.bTo = to;
      this.bFrom = from;
      NProgress.start()// 开始进度条
      const menuStore = useMenuStore();
      menuStore.setRoute(to);

      this.checkPermission();
      if(to.path === '/Login') {
		  // window.open('/show/#/Login','_self')
          next();
      }else {
        if (Cookies.get('token') ) {
          next();
        } else {
          ElNotification({title: '登录失效', type: 'warning', message: '请先登录'})
	        // window.open('/show/#/Login','_self')
          this.router.push('/student/Login')
        }
      }
    });

    router.afterEach((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
      this.bTo = to;
      this.bFrom = from;
      NProgress.done()// 结束进度条
    });
  }

  // checkPermission() {
  //   // 默认校验Token
  //   const authUserStore = useAuthUserStore();
  //   if (this.bTo!.meta.permission === undefined || this.bTo!.meta.permission === true) {
  //     !authUserStore.isAuth && (
  //       ElNotification({ title: '登录失效', type: 'warning', message: '请先登录' }),
  //       this.router.push('/Login')
  //     );
  //   }
  // }
	checkPermission() {
	    // 后端验证token 是否有效
		// 默认校验Token
		const token = Cookies.get('token') !== ''
		if (this.bTo!.meta.permission === undefined || this.bTo!.meta.permission === true) {
			!token && (
				ElNotification({ title: '登录失效', type: 'warning', message: '请先登录' }),
                    this.router.push('/student/Login')
			);
		}
	}
}

export default RouterWatching;
